import { defineStore } from "pinia";
import { ref, reactive } from "vue";

export const useChatStore = defineStore("chat", () => {
    const wsUrl = `${window.link}/chat?access-token=${localStorage.getItem("access-token")}`;
    const socket = ref(null);
    const onlineUsers = ref([]); // 在线用户列表
    const messages = reactive([]); // 消息列表
    const targetUser = ref(""); // 当前选择的目标用户
    const message = ref(""); // 当前输入的消息

    // 初始化 WebSocket
    const initWebSocket = () => {
        socket.value = new WebSocket(wsUrl);

        socket.value.onopen = () => {
            console.log("WebSocket 已连接");
        };

        socket.value.onmessage = (event) => {
            const data = JSON.parse(event.data);
            console.log(data);

            if (data.system) {
                // 更新在线用户列表
                onlineUsers.value = data.message;
            } else {
                // 普通消息
                messages.push({
                    sender: data.fromName || "系统",
                    text: data.message,
                    isSelf: false,
                });
            }
        };

        socket.value.onclose = () => {
            console.log("WebSocket 已断开");
        };

        socket.value.onerror = (error) => {
            console.error("WebSocket 错误:", error);
        };
    };

    // 发送消息
    const sendMessage = () => {
        if (!message.value || !targetUser.value) {
            alert("请选择用户并输入消息");
            return;
        }

        const msg = {
            target: targetUser.value,
            message: message.value,
        };
        socket.value.send(JSON.stringify(msg));

        messages.push({
            sender: "我",
            text: message.value,
            isSelf: true,
        });

        message.value = ""; // 清空输入框
    };

    // 选择用户
    const selectUser = (user) => {
        targetUser.value = user;
    };

    // 启动 WebSocket
    initWebSocket();

    return {
        onlineUsers,
        messages,
        targetUser,
        message,
        sendMessage,
        selectUser,
    };
});